package com.glory.brepda.activity.mfg;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.AddCarrierDataAdapter;
import com.glory.brepda.adapter.DefectListAdapter;
import com.glory.brepda.adapter.EDCListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.DefectCodeEntity;
import com.glory.brepda.entity.EDCListBean;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.ScrapEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class WBWorkEndActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvEqpWorkID)
    TextView tvEqpWorkID;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.etTrackOutNum)
    EditText etTrackOutNum;
    @BindView(R.id.etProjectNum)
    FreeUI_ClearEditText etProjectNum;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.etMaterielModel)
    FreeUI_ClearEditText etMaterielModel;
    @BindView(R.id.rvMaterielModelList)
    RecyclerView rvMaterielModelList;
    @BindView(R.id.etMaterielBox)
    FreeUI_ClearEditText etMaterielBox;
    @BindView(R.id.rvMaterielBoxList)
    RecyclerView rvMaterielBoxList;
//    @BindView(R.id.ivDefectArrow)
//    ImageView ivDefectArrow;
//    @BindView(R.id.flDefectList)
//    FrameLayout flDefectList;
    @BindView(R.id.rvScrapList)
    RecyclerView rvScrapList;
    @BindView(R.id.rvEdcDataList)
    RecyclerView rvEdcDataList;
    @BindView(R.id.tvScrapNum)
    TextView tvScrapNum;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.llEap)
    LinearLayout llEap;
    @BindView(R.id.rlEap)
    RelativeLayout rlEap;
    @BindView(R.id.tvDefectListTitle)
    TextView tvDefectListTitle;
    @BindView(R.id.tvPauseStatus)
    TextView tvPauseStatus;
    @BindView(R.id.lotScan)
    ImageView lotScan;
    @BindView(R.id.modelScan)
    ImageView modelScan;
    @BindView(R.id.boxScan)
    ImageView boxScan;
    private static final int REQUEST_CODE_TEXT1 = 1001;
    private static final int REQUEST_CODE_TEXT2 = 1002;
    private static final int REQUEST_CODE_TEXT3 = 1003;
    private List<String> defectCodeList;
    private FreeUI_GeneralPop codePop;
    private DefectListAdapter defectListAdapter;
    private EDCListAdapter edcListAdapter;
    private LotInfoEntity lotInfoEntity;
    private AddCarrierDataAdapter materielModelAdapter;
    private AddCarrierDataAdapter materielBoxAdapter;
    private String equipmentid;
    private String mDurable;
    private List<String> mDurablelist;
    private List<ScrapEntity> scrapEntityList;
    private String defectCode = "";
    private String subqty = "";
    private String title;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_commonly;
    }

    @Override
    protected void initView() {
        title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        etLot.requestFocus();
        tvBaseSubmit.setText("下一步");
        rvEdcDataList.setVisibility(View.GONE);
        rlEap.setVisibility(View.GONE);
        llEap.setVisibility(View.GONE);
        rvEdcDataList.setVisibility(View.GONE);
        defectCodeList = new ArrayList<>();
        initRecyclerView(rvScrapList, this);
        defectListAdapter = new DefectListAdapter(null, tvScrapNum,false);
        defectListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        defectListAdapter.isFirstOnly(true);
        rvScrapList.setAdapter(defectListAdapter);

        defectListAdapter.setListener(new DefectListAdapter.onListener() {
            @Override
            public void OnListener(String s, ScrapEntity item) {
                try {
                    item.setMAINQTY(s.toString());

                    item.setMAINQTY(s.toString());
                    item.setSUBQTY(s.toString());
                    ScrapEntity.MainQTY mainQTY = new ScrapEntity.MainQTY(s.toString());
                    List<ScrapEntity.MainQTY> data = new ArrayList<>();
                    data.add(mainQTY);
                    item.setQTYLIST(data);
                    long num = defectListAdapter.Calculation();
                    if (num < 0) {
                        FreeApi_ToastUtils.showFreeToast("不良数量大于批次数量，请重新输入", MyApp.app, false, Toast.LENGTH_LONG);
                        item.setMAINQTY("0");
                        item.setSUBQTY("0");
                        ScrapEntity.MainQTY mainQTY1 = new ScrapEntity.MainQTY("0");
                        List<ScrapEntity.MainQTY> data1 = new ArrayList<>();
                        data.add(mainQTY1);
                        item.setQTYLIST(data1);
                        tvScrapNum.setText("0");
                    } else {
                        tvScrapNum.setText(num + "");
                    }

                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });


        edcListAdapter = new EDCListAdapter(null);
        edcListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        edcListAdapter.isFirstOnly(true);
        rvEdcDataList.setAdapter(edcListAdapter);

        initRecyclerView(rvMaterielModelList, this);
        initRecyclerView(rvMaterielBoxList, this);
        initRecyclerView(rvEdcDataList, this);
        materielModelAdapter = getCarrierAdapter();
        rvMaterielModelList.setAdapter(materielModelAdapter);
        materielBoxAdapter = getCarrierAdapter();
        rvMaterielBoxList.setAdapter(materielBoxAdapter);

        initEdit(etLot, s -> {
            //获取lot信息
            LotUtils.searchLotInfo(WBWorkEndActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    lotInfoEntity = response;
                    mDurable = response.getLOT().getDURABLEID();
                    subqty = response.getLOT().getMAINQTY();
                    equipmentid = lotInfoEntity.getLOT().getEQUIPMENTID();
                    tvStep.setText(response.getLOT().getSTEPNAME() + "/" + response.getLOT().getSTEPDESC());
                    etProjectNum.setText(String.valueOf(response.getPACKAGETYPEQTY()));
//                    mDurablelist = response.getDURABLELIST();
//                    materielModelAdapter.setNewData(mDurablelist);
                    etTrackOutNum.setText(response.getLOT().getMAINQTY());
                    tvEqpWorkID.setText(response.getLOT().getEQUIPMENTID());
                    tvLotState.setText(response.getLOT().getSTATE());
                    defectListAdapter.setTotalNum(Integer.parseInt(response.getLOT().getMAINQTY()));
                    getDefectInfo(response.getSTEPLIST().get(0).getSCRAPCODESRC());
                    tvPauseStatus.setText(response.getLOT().getHOLDSTATE());
//                    getData();
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });


        initEdit(etMaterielModel, s -> {
            if (etLot.equals("")){
                showToast("请先扫描批次号!", false);
                return;
            }

            if (materielModelAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }

            materielModelAdapter.getData().add(s);
            materielModelAdapter.notifyDataSetChanged();
        });

        initEdit(etMaterielBox, s -> {
            if (etLot.equals("")){
                showToast("请先扫描批次号!", false);
                return;
            }

            if (materielBoxAdapter.getData().contains(s)) {
                showToast("当前料盒已添加到列表中", false);
                return;
            }

            materielBoxAdapter.getData().add(s);
            materielBoxAdapter.notifyDataSetChanged();
            etMaterielBox.setText("");
            etMaterielBox.requestFocus();
        });

//        etTrackOutNum.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable editable) {
//                defectListAdapter.setTotalNum(editable.toString().equals("")?0:Integer.parseInt(editable.toString()));
//            }
//        });

    }

    private void getData() {
        FreeUI_EntityCallBack<BaseResponseBean<EDCListBean>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EDCListBean>>
                (new TypeToken<BaseResponseBean<EDCListBean>>() {
                }.getType(),getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EDCListBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(WBWorkEndActivity.this, false, getSupportFragmentManager())) {
                    edcListAdapter.setNewData(response.body().getResponse().getBody().getList());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EDCListBean>> response) {
                super.onError(response);
                FreeApi_LogUtils.saveErrorMessages(response.getException(), "TrackOutEDC");
                FreeApi_ToastUtils.showFreeToast("连接服务器失败", WBWorkEndActivity.this, false, 0);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID", tvEqpWorkID.getText().toString());
        map.addProperty("LOTID", getText(etLot));
        NetUtils.requestPostNet("TrackOutEDC", "TrackOutEDC", WBWorkEndActivity.this, map, callBack);

    }

    private void getDefectInfo(String defectcodesrc) {

        FreeUI_EntityCallBack<BaseResponseBean<DefectCodeEntity>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<DefectCodeEntity>>
                (new TypeToken<BaseResponseBean<DefectCodeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    defectCodeList.clear();
                    List<DefectCodeEntity.DefectCode> scrapcodelists = response.body().getResponse().getBody().getADREFLIST();
                    for (DefectCodeEntity.DefectCode code : scrapcodelists){
                        defectCodeList.add(code.getKEY() + "/" + code.getDESCRIPTION());
                        ScrapEntity scrapEntity = new ScrapEntity();
                        scrapEntity.setACTIONCODE(code.getKEY());
                        scrapEntity.setACTIONREASON(code.getDESCRIPTION());
                        scrapEntity.setLOTID(lotInfoEntity.getLOT().getLOTID());
                        scrapEntity.setLOTRRN(lotInfoEntity.getLOT().getOBJECTRRN());
                        scrapEntity.setACTIONTYPE("Scrap");
//                        scrapEntity.setSUBQTY("");
                        scrapEntity.setSUBQTY(subqty+"");
                        if (defectListAdapter.getData().size() > 0) {
                            if (containCode(scrapEntity)) {
                                defectListAdapter.addData(scrapEntity);
                            }
                        } else {
                            defectListAdapter.addData(scrapEntity);
                        }
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"GETSTEPBYLOT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCENAME", defectcodesrc);
//        map.addProperty("REFERENCENAME", Constant.REFERENCENAME);
//        map.add("REFERENCETYPE", new JsonParser().parse(new Gson().toJson(new LotList(s))).getAsJsonObject());//传批次集合
        map.addProperty("REFERENCETYPE","USER");
        NetUtils.requestPostNet("IF.ADREFLISTQUERY", "Common", WBWorkEndActivity.this, map, callback);
    }

    @Override
    protected void initData() {


        lotScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT1);
            }
        });
        modelScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT2);
            }
        });
        boxScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT3);
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && data != null) {
            String qrResult = data.getStringExtra("SCAN_RESULT"); // 获取扫码结果
            if (qrResult != null) {
                switch (requestCode) {
                    case REQUEST_CODE_TEXT1:
                        etLot.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT2:
                        etMaterielModel.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT3:
                        etMaterielBox.setText(qrResult);
                        break;
                }
            }

        }
        if (requestCode == 1) {
            finish();
        }
    }


    @OnClick({R.id.tvBaseSubmit,R.id.tvGetEDCData})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit24")) {
//                    return;
//                }

                if (getText(etLot).equals("")){
                    showToast("请先扫描批次信息",false);
                    return;
                }

                if (tvLotState.getText().toString().equals("待投产")){
                    showConfirmDialog("批次未投产，请联系计划部执行投产");
                    return;
                }

//                if (tvLotState.getText().toString().equals("等待作业")){
//                    showConfirmDialog("批次没有作业，请操作进站功能");
//                    return;
//                }

                List<String> data = materielModelAdapter.getData();

//                if (!tvDefectNum.getText().toString().equals("")){
//                    int defectNum = Integer.parseInt(tvDefectNum.getText().toString());
//                    etTrackOutNum.setText(String.valueOf(Integer.parseInt(getText(etTrackOutNum)) - defectNum));
//                }
//                String trackOutNum = "0";
//                if (!tvDefectNum.getText().toString().equals("")){
//                    int defectNum = Integer.parseInt(tvDefectNum.getText().toString());
//                    trackOutNum = String.valueOf(Integer.parseInt(etTrackOutNum.getText().toString()) - defectNum);
//                }

                int sumDefect = 0;
                if (defectListAdapter.getData() != null) {
                    for (ScrapEntity entity : defectListAdapter.getData()) {
                        sumDefect += Integer.parseInt(entity.getMAINQTY().equals("") ? "0" : entity.getMAINQTY());
                    }
                } else {
                    sumDefect += 0;
                }
                tvScrapNum.setText(sumDefect + "");
                String defectNum = tvScrapNum.getText().toString().equals("") ? "0" : tvScrapNum.getText().toString();
                int defect = Integer.parseInt(defectNum) + Integer.parseInt(getText(etTrackOutNum));

                if (defect != Integer.parseInt(lotInfoEntity.getLOT().getMAINQTY())) {
                    showToast("报废数量输入不正确", false);
                    return;
                }

                List<String> dataBox = materielBoxAdapter.getData();
                data.addAll(dataBox);
                Bundle bundle = new Bundle();
                bundle.putString("LOTID",getText(etLot));
                bundle.putString("EQPID",tvEqpWorkID.getText().toString());
                bundle.putString("DEFECTCODE",defectNum);
                bundle.putString("SCRAPCODESRC",tvScrapNum.getText().toString().equals("")?"0":tvScrapNum.getText().toString());
                bundle.putString("TRACKOUTNUM",getText(etTrackOutNum));
                bundle.putSerializable("LOTINFOENTITY", lotInfoEntity);
                bundle.putString("method","MULTIDEVICELOTTRACKOUT");
                bundle.putString("title",title);
                bundle.putStringArrayList("MATERIELMODELLIST", (ArrayList<String>) data);
                bundle.putSerializable("ScrapList", (Serializable)defectListAdapter.getData());

                Intent intent = new Intent(this, WBWorkEnd2Activity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent,1);
                break;
//            case R.id.flDefectList:
//                if (defectCodeList.size() <= 0) {
//                    showToast("未获取到不良代码列表", false);
//                    return;
//                }
//
//                if (codePop != null) {
//                    if (codePop.isShowing()) {
//                        codePop.dismiss();
//                    }
//                } else {
//                    codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flDefectList.getWidth(), defectCodeList, ivDefectArrow, (codeS, i) -> {
//                        tvDefectCode.setText(codeS.split("/")[0]);
//                        ScrapEntity scrapEntity = new ScrapEntity();
//                        scrapEntity.setACTIONCODE(codeS.split("/")[0]);
//                        scrapEntity.setACTIONREASON(codeS.split("/")[1]);
//                        scrapEntity.setLOTID(lotInfoEntity.getLOT().getLOTID());
//                        scrapEntity.setLOTRRN(lotInfoEntity.getLOT().getOBJECTRRN());
//                        scrapEntity.setACTIONTYPE("Scrap");
//                        defectCode = codeS.split("/")[0];
//                        if (defectListAdapter.getData().size() > 0) {
//                            if (containCode(scrapEntity)) {
//                                defectListAdapter.addData(scrapEntity);
//                            }
//                        } else {
//                            defectListAdapter.addData(scrapEntity);
//                        }
//
//                    });
//                }
//                FreeApi_PopUtils.setArrowShow(ivDefectArrow);
//                codePop.showAsDropDown(flDefectList, 0, 0);
//                break;
            case R.id.tvGetEDCData:
                FreeUI_EntityCallBack<BaseResponseBean<EDCListBean>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EDCListBean>>
                        (new TypeToken<BaseResponseBean<EDCListBean>>() {
                        }.getType(),getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<EDCListBean>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(WBWorkEndActivity.this, false, getSupportFragmentManager())) {
                            edcListAdapter.setNewData(response.body().getResponse().getBody().getList());
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<EDCListBean>> response) {
                        super.onError(response);
                        FreeApi_LogUtils.saveErrorMessages(response.getException(), "TrackOutEDC");
                        FreeApi_ToastUtils.showFreeToast("连接服务器失败", WBWorkEndActivity.this, false, 0);
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("EQUIPMENTID", tvEqpWorkID.getText().toString());
                map.addProperty("LOTID", getText(etLot));
                NetUtils.requestPostNet("TrackOutEDC", "TrackOutEDC", WBWorkEndActivity.this, map, callBack);
                break;
        }
    }



    private boolean containCode(ScrapEntity scrapEntity) {
//        for (ScrapEntity bean : defectListAdapter.getData()) {
//            if (bean.getACTIONCODE().equals(scrapEntity.getACTIONCODE())) {
//                showToast("列表中已有当前不良代码!", false);
//                return false;
//            }
//        }
        return true;
    }
}